using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Infrastructure.Redis
{
    /// <summary>
    /// Redis服务扩展类
    /// </summary>
    public static class RedisServiceExtensions
    {
        /// <summary>
        /// 添加Redis服务
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <param name="configuration">配置</param>
        /// <returns>服务集合</returns>
        public static IServiceCollection AddRedisService(this IServiceCollection services, IConfiguration configuration)
        {
            // 从配置中读取Redis配置
            var redisSection = configuration.GetSection("Redis");
            
            // 配置Redis选项
            services.Configure<RedisOptions>(options =>
            {
                options.Host = redisSection["Host"] ?? "localhost";
                options.Port = int.TryParse(redisSection["Port"], out int port) ? port : 6379;
                options.DefaultDatabase = int.TryParse(redisSection["DefaultDatabase"], out int db) ? db : 0;
                options.ConnectTimeout = int.TryParse(redisSection["ConnectTimeout"], out int connectTimeout) ? connectTimeout : 5000;
                options.SyncTimeout = int.TryParse(redisSection["SyncTimeout"], out int syncTimeout) ? syncTimeout : 10000;
                options.UseSsl = bool.TryParse(redisSection["UseSsl"], out bool useSsl) && useSsl;
                options.Password = redisSection["Password"];
                options.RetryCount = int.TryParse(redisSection["RetryCount"], out int retryCount) ? retryCount : 3;
                options.RetryDelay = int.TryParse(redisSection["RetryDelay"], out int retryDelay) ? retryDelay : 200;
                options.KeyPrefix = redisSection["KeyPrefix"] ?? string.Empty;
            });
            
            // 注册Redis服务
            services.AddSingleton<IRedisHelper, RedisHelper>();
            
            return services;
        }
        
        /// <summary>
        /// 添加Redis服务（使用自定义配置）
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <param name="configureOptions">配置选项</param>
        /// <returns>服务集合</returns>
        public static IServiceCollection AddRedisService(this IServiceCollection services, Action<RedisOptions> configureOptions)
        {
            // 配置Redis选项
            services.Configure(configureOptions);
            
            // 注册Redis服务
            services.AddSingleton<IRedisHelper, RedisHelper>();
            
            return services;
        }
    }
} 